﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CHATCENTRAL.Interfaces.Mappers;
using CHATCENTRAL.Interfaces.Entities;
using ChatInterfaces;
using System.ServiceModel;

namespace CHATCENTRAL.MAPPERS
{
    public class ClientMapper : IClientMapper
    {
        private static ClientMapper inst;

        private List<IClient> lstClients;

        //private static object myLock = new object();

        public static ClientMapper GetInstance()
        {
            if (inst == null)
                    inst = new ClientMapper();

            return inst;
        }

        private ClientMapper()
        {
            lstClients = new List<IClient>();
        }

        public void AddUser(IClient user)
        {
            if (user == null)
                throw new NullReferenceException();

            if (lstClients.Contains(user))
                throw new Exception("Este Utilizador já existe");

            lstClients.Add(user);
        }

        public IClient GetUser(string username, string pwd)
        {
            IClient client = lstClients.SingleOrDefault(d => d.username == username && d.pwd == pwd);

            if (client == null)
            {
                FaultContract fc = new FaultContract();
                fc.Msg = "Utilizador não existente";
                throw new FaultException<FaultContract>(fc, new FaultReason(fc.Msg));
            }
            
            return client;
        }

        public IClient GetUser(string username)
        {
            IClient client = lstClients.SingleOrDefault(d => d.username == username);

            if (client == null)
            {
                FaultContract fc = new FaultContract();
                fc.Msg = "Utilizador não existente";
                throw new FaultException<FaultContract>(fc);
            }

            return client;
        }

        public IEnumerable<IClient> GetAllUsers()
        {
            return lstClients;
        }
    }
}
